package cn.fbs.service;

import cn.fbs.dao.dm.*;
import cn.fbs.dao.oracle.OracleTargetMapper;
import cn.fbs.model.TDataInfo;
import cn.fbs.model.TImageInfo;
import cn.fbs.model.TVideoInfo;
import cn.fbs.param.ImageParam;
import cn.fbs.param.UploadParam;
import cn.fbs.param.VideoParam;
import cn.fbs.util.*;
import cn.fbs.util.imageshort.FileUtil;
import lombok.extern.java.Log;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
@Log
public class AssignService {
    @Value("${resource.locations}")
    private String resourceLocations;

    @Value(("${compressRatio}"))
    private Integer compressRatio;

    @Value(("${maxJoinNum}"))
    private int maxJoinNum;

    @Autowired
    private DMImageInfoMapper imageInfoMapper;

    @Autowired
    private DMNewTargetMapper targetMapper;


    /**
     * 赋予视频媒体信息
     */
    public void giveVideoInfo(VideoParam uploadParam, TVideoInfo videoInfo) {
        if (uploadParam.getRealFileUrl() == null) {
            return;
        }
        String fileUrl = uploadParam.getRealFileUrl();
        File file = new File(fileUrl);
        if (!file.exists()) {
            return;
        }
        videoInfo.setFileUrl(fileUrl.replace(resourceLocations, ""));
        File localFile = new File(fileUrl);
        try {
            String imgBase64 = VideoUtil.fetchFrame(fileUrl, compressRatio);
            videoInfo.setThumbnail(imgBase64);
        } catch (Exception e) {
            log.warning("500,视频生成缩略图出现异常");
            log.info(e.getMessage());
            e.printStackTrace();
        }

        Integer fileSize = Math.toIntExact(localFile.length());
        videoInfo.setFileSize(fileSize);
        videoInfo.setFileType(VideoUtil.getVideoFormat(fileUrl));
//        videoInfo.setUploadFileName(file.getName());
        long mp4Duration = 0;
        try {
            mp4Duration = VideoUtil.getMp4Duration(fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }

        videoInfo.setDuration(Long.toString(mp4Duration));
    }

    /**
     * 赋予资料文档媒体信息
     */
    public void giveDataInfo(UploadParam uploadParam, TDataInfo dataInfo) {
        if (uploadParam.getRealFileUrl() == null) {
            return;
        }
        String fileUrl = uploadParam.getRealFileUrl();
        File file = new File(fileUrl);
        if (!file.exists()) {
            return;
        }
        dataInfo.setFileUrl(fileUrl.replaceFirst(resourceLocations, ""));
        File localFile = new File(fileUrl);
        try {
            String fileSuf = fileUrl.substring(fileUrl.lastIndexOf(".") + 1);
            String pdfPath = fileUrl.substring(0, fileUrl.lastIndexOf(".")) + ".pdf";
            String thumbnailPath = fileUrl.substring(0, fileUrl.lastIndexOf(".")) + ".jpg";
            /**
             * 区分是什么文件类型
             */
            if (fileSuf.equalsIgnoreCase("doc") || fileSuf.equalsIgnoreCase("docx")) {
                WordToPdfUtil.wordToPdf(fileUrl, pdfPath);
            }
            if (fileSuf.equalsIgnoreCase("ppt") || fileSuf.equalsIgnoreCase("pptx")) {
                FileToPdfUtils.pptToWord(fileUrl, pdfPath);
            }
            String imgBase64 = PdfUtil.getThumbnails(pdfPath, thumbnailPath, compressRatio);
            dataInfo.setThumbnail(imgBase64);
            int numberOfPages = PdfUtil.getNumberOfPages(pdfPath);
            dataInfo.setPageNumber(numberOfPages);
            String pdfContent = PdfUtil.getContent(pdfPath);
            String[] keyWords = WordUtil.getKeyWords(pdfContent);
            StringBuilder keywordStr = new StringBuilder();
            for (int i = 0; i < keyWords.length; i++) {
                if (i == 0) {
                    keywordStr.append(keyWords[i]);
                } else {
                    keywordStr.append(",").append(keyWords[i]);
                }
            }
            dataInfo.setKeyword(keywordStr.toString());
        } catch (Exception e) {
            log.warning("500,资料生成缩略图出现异常");
        }
        Integer fileSize = Math.toIntExact(localFile.length());
        dataInfo.setFileSize(fileSize);
        dataInfo.setFileType(VideoUtil.getVideoFormat(fileUrl));
//        dataInfo.setUploadFileName(file.getName());
    }

    /**
     * 赋予图像媒体信息
     */
    public void giveImageInfo(ImageParam uploadParam, TImageInfo imageInfo) throws IOException {
        if (uploadParam.getRealFileUrl() == null) {
            return;
        }

        String fileUrl = uploadParam.getRealFileUrl();
        File file = new File(fileUrl);
        if (!file.exists()) {
            return;
        }
        imageInfo.setFileUrl(fileUrl.replace(resourceLocations, ""));
        File localFile = new File(fileUrl);
        String thumbnail = "";
        if (fileUrl.endsWith("tif")) {
            String pngPath = fileUrl.substring(0, fileUrl.lastIndexOf(".")) + ".png";
            thumbnail = FileUtil.getCompressBase64FromUrl(new File(pngPath), compressRatio);
        } else {
            thumbnail = FileUtil.getCompressBase64FromUrl(localFile, 5);
        }
        imageInfo.setThumbnail(thumbnail);
        long length = localFile.length();

        Integer fileSize = Math.toIntExact(length);
        imageInfo.setFileSize(fileSize);
        if (file.getName().contains(".")) {
            {
                String fileType = file.getName().substring(file.getName().lastIndexOf(".") + 1);
                imageInfo.setFileType(fileType);
            }
        }
        BufferedImage bufferedImage = null;
        try {
            FileInputStream fileInputStream = new FileInputStream(localFile);
            bufferedImage = ImageIO.read(fileInputStream);
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (bufferedImage != null) {
            imageInfo.setImageSize(bufferedImage.getHeight() + "x" + bufferedImage.getWidth());
        }
//        imageInfo.setUploadFileName(file.getName());
    }


    public TImageInfo xmlGiveImageInfo(Element objectElement, String taskName, String xmlDir) throws RuntimeException, IOException {
        String fullName = objectElement.attributeValue("name");
        TImageInfo imageInfo = new TImageInfo();
        imageInfo.setTaskName(taskName);
        String FileName = fullName;
        if (fullName.contains(".")) {
            FileName = fullName.substring(0, fullName.lastIndexOf("."));
        }
        imageInfo.setFileName(FileName);
        String newFilePath = xmlDir + "/" + fullName;
        imageInfo.setFileUrl(newFilePath.replaceFirst(resourceLocations, ""));
        File localFile = new File(newFilePath);
        String thumbnail = null;

        try {
            thumbnail = FileUtil.getCompressBase64FromUrl(localFile, compressRatio);
        } catch (IOException e) {
            e.printStackTrace();
        }
        /**
         * 如果是tif，生成同名不同后缀的图片
         */
        String suf = newFilePath.substring(newFilePath.lastIndexOf(".") + 1);
        if (suf.equalsIgnoreCase("tif") || suf.equalsIgnoreCase("tiff")) {
            String pngPath = newFilePath.substring(0, newFilePath.lastIndexOf(".")) + ".png";
            FileUtil.getCompressBase64FromUrl2(new File(newFilePath), 1, pngPath);
        }
        imageInfo.setThumbnail(thumbnail);
        Integer fileSize = Math.toIntExact(localFile.length());
        imageInfo.setFileSize(fileSize);
        if (fullName.contains(".")) {
            {
                String fileType = fullName.substring(fullName.lastIndexOf(".") + 1);
                imageInfo.setFileType(fileType);
            }
        }
        BufferedImage bufferedImage = null;
        try {
            FileInputStream fileInputStream = new FileInputStream(localFile);
            bufferedImage = ImageIO.read(fileInputStream);
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        imageInfo.setImageSize(bufferedImage.getHeight() + "x" + bufferedImage.getWidth());
        imageInfo.setUploadFileName(fullName);
        List<Element> elements = objectElement.elements();
        for (Element element : elements) {
            if (element.getName().equals("侦照对象")) {
                String zzdx = element.getText();
                imageInfo.setZzdx(zzdx);
                String targetId = targetMapper.selectIdByTargetName(zzdx);
                if (imageInfoMapper.selectCountByzzdx(zzdx) >= maxJoinNum) {
                    throw new RuntimeException("400,目标关联数据超过最大限制!");
                }
                if (targetId != null) {
                    imageInfo.setTargetType(targetId);
                }
            }
        }
        imageInfo.setCreateDate(new Date());
        return imageInfo;
    }

    public TVideoInfo xmlGiveVideoInfo(Element objectElement, String taskName, String xmlDir) throws IOException {
        String fullName = objectElement.attributeValue("name");
        TVideoInfo videoInfo = new TVideoInfo();
        videoInfo.setTaskName(taskName);
        String FileName = fullName;
        if (fullName.contains(".")) {
            FileName = fullName.substring(0, fullName.lastIndexOf("."));
        }
        videoInfo.setFileName(FileName);
        String newFilePath = xmlDir + "/" + fullName;
        videoInfo.setFileUrl(newFilePath.replaceFirst(resourceLocations, ""));
        try {
            String imgBase64 = VideoUtil.fetchFrame(newFilePath, compressRatio);
            videoInfo.setThumbnail(imgBase64);
        } catch (Exception e) {
            log.warning("500,视频生成缩略图出现异常");
        }
        File localFile = new File(newFilePath);
        Integer fileSize = Math.toIntExact(localFile.length());
        videoInfo.setFileSize(fileSize);
        if (fullName.contains(".")) {
            {
                String fileType = fullName.substring(fullName.lastIndexOf(".") + 1);
                videoInfo.setFileType(fileType);
            }
        }
        videoInfo.setUploadFileName(fullName);
        List<Element> elements = objectElement.elements();
        for (Element element : elements) {
            if (element.getName().equals("侦照对象")) {
                String zzdx = element.getText();
                videoInfo.setZzdx(zzdx);
                String targetId = targetMapper.selectIdByTargetName(zzdx);
                if (imageInfoMapper.selectCountByzzdx(zzdx) >= maxJoinNum) {
                    throw new RuntimeException("400,目标关联数据超过最大限制!");
                }
                if (targetId != null) {
                    videoInfo.setTargetType(targetId);
                }
            }
        }

        videoInfo.setCreateDate(new Date());
        return videoInfo;
    }


}
